<template>
  <div class="map-chart-wrapper">
    <div ref="mapChart" class="chart-container"></div>
    <div v-if="loading" class="chart-loading">
      <el-icon class="is-loading"><Loading /></el-icon>
      <span>加载中...</span>
    </div>
    <div v-if="!loading && isEmpty" class="chart-empty">
      <el-empty description="暂无数据" />
    </div>
  </div>
</template>

<script setup>
import { nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
import * as echarts from 'echarts'
import { Loading } from '@element-plus/icons-vue'

const props = defineProps({
  // 图表标题
  title: {
    type: String,
    default: ''
  },
  // 数据
  data: {
    type: Array,
    default: () => []
  },
  // 图表高度
  height: {
    type: String,
    default: '400px'
  },
  // 是否显示视觉映射
  showVisualMap: {
    type: Boolean,
    default: true
  },
  // 动画效果
  animation: {
    type: Boolean,
    default: true
  }
})

const mapChart = ref(null)
let chartInstance = null
const loading = ref(false)
const isEmpty = ref(false)

// 中国省份坐标（用于散点图展示）
const provinceCoords = {
  '北京': [116.4074, 39.9042],
  '上海': [121.4737, 31.2304],
  '广东': [113.2644, 23.1291],
  '江苏': [118.7969, 32.0603],
  '浙江': [120.1536, 30.2875],
  '山东': [117.0208, 36.6682],
  '四川': [104.0665, 30.5723],
  '河南': [113.6254, 34.7466],
  '湖北': [114.3055, 30.5931],
  '湖南': [112.9388, 28.2282],
  '福建': [119.2965, 26.1004],
  '天津': [117.2008, 39.0842],
  '重庆': [106.5516, 29.5630],
  '辽宁': [123.4328, 41.8045],
  '河北': [114.5149, 38.0428],
  '陕西': [108.9540, 34.2656],
  '安徽': [117.2272, 31.8206],
  '江西': [115.8581, 28.6832],
  '云南': [102.7103, 25.0406],
  '贵州': [106.7070, 26.5982]
}

// 初始化图表配置
const getOption = () => {
  // 将数据转换为散点图格式
  const scatterData = props.data.map(item => ({
    name: item.name,
    value: [
      ...(provinceCoords[item.name] || [116.4074, 39.9042]),
      item.value
    ]
  }))

  // 获取最大值用于视觉映射
  const maxValue = Math.max(...props.data.map(d => d.value), 1)

  return {
    title: props.title ? {
      text: props.title,
      left: 'center',
      top: '10',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#333'
      }
    } : null,
    tooltip: {
      trigger: 'item',
      formatter: (params) => {
        if (params.componentSubType === 'scatter') {
          return `${params.name}<br/>销售额: ¥${params.value[2]?.toLocaleString() || 0}万`
        }
        return params.name
      },
      backgroundColor: 'rgba(50, 50, 50, 0.9)',
      borderColor: '#333',
      borderWidth: 1,
      textStyle: {
        color: '#fff'
      }
    },
    visualMap: props.showVisualMap ? {
      show: true,
      min: 0,
      max: maxValue,
      left: 'left',
      bottom: '20',
      text: ['高', '低'],
      inRange: {
        color: ['#e0f3f8', '#abd9e9', '#74add1', '#4575b4', '#313695']
      },
      calculable: true,
      textStyle: {
        color: '#666'
      }
    } : null,
    geo: {
      map: 'china',
      roam: true,
      center: [105, 36],
      zoom: 1.2,
      label: {
        show: false
      },
      itemStyle: {
        areaColor: '#f3f3f3',
        borderColor: '#999',
        borderWidth: 0.5
      },
      emphasis: {
        itemStyle: {
          areaColor: '#e6f0ff'
        },
        label: {
          show: true,
          color: '#333'
        }
      }
    },
    series: [
      {
        type: 'scatter',
        coordinateSystem: 'geo',
        data: scatterData,
        symbolSize: (val) => {
          return Math.max(val[2] / maxValue * 40 + 10, 10)
        },
        label: {
          show: false
        },
        itemStyle: {
          color: '#f56c6c',
          shadowBlur: 10,
          shadowColor: 'rgba(245, 108, 108, 0.5)'
        },
        emphasis: {
          label: {
            show: true,
            formatter: '{b}',
            position: 'top',
            color: '#333',
            fontSize: 12
          },
          itemStyle: {
            color: '#ff4d4f',
            shadowBlur: 20
          }
        }
      },
      {
        type: 'effectScatter',
        coordinateSystem: 'geo',
        data: scatterData.slice(0, 5), // 只对前5个显示涟漪效果
        symbolSize: (val) => {
          return Math.max(val[2] / maxValue * 40 + 10, 10)
        },
        showEffectOn: 'render',
        rippleEffect: {
          brushType: 'stroke',
          scale: 3,
          period: 4
        },
        label: {
          show: false
        },
        itemStyle: {
          color: '#ff7875',
          shadowBlur: 10,
          shadowColor: 'rgba(255, 120, 117, 0.5)'
        }
      }
    ],
    animation: props.animation
  }
}

// 初始化图表
const initChart = () => {
  if (!mapChart.value) return

  // 如果实例已存在，先销毁
  if (chartInstance) {
    chartInstance.dispose()
  }

  // 注册中国地图（简化版）
  echarts.registerMap('china', {
    type: 'FeatureCollection',
    features: [] // 简化版，实际使用需要完整的 GeoJSON 数据
  })

  chartInstance = echarts.init(mapChart.value)
  chartInstance.setOption(getOption())

  // 添加窗口大小改变监听
  window.addEventListener('resize', handleResize)
}

// 处理窗口大小改变
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 加载数据
const loadData = () => {
  if (!props.data || props.data.length === 0) {
    isEmpty.value = true
    return
  }

  isEmpty.value = false
  nextTick(() => {
    initChart()
  })
}

// 监听数据变化
watch(() => props.data, () => {
  loadData()
}, { deep: true })

onMounted(() => {
  loadData()
})

onUnmounted(() => {
  if (chartInstance) {
    window.removeEventListener('resize', handleResize)
    chartInstance.dispose()
    chartInstance = null
  }
})

// 暴露刷新方法
defineExpose({
  refresh: loadData,
  getInstance: () => chartInstance
})
</script>

<style scoped lang="scss">
.map-chart-wrapper {
  position: relative;
  width: 100%;
  height: v-bind(height);

  .chart-container {
    width: 100%;
    height: 100%;
  }

  .chart-loading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    color: #999;
    font-size: 14px;

    .el-icon {
      font-size: 32px;
    }
  }

  .chart-empty {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 100%;
  }
}
</style>

